package com.sky.service.userImpl;

import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;

import com.sky.mapper.DishFlavorMapper;

import com.sky.mapper.DishMapper;

import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service("UserDishServiceImpl")
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //判空
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<DishVO> dishVOS = (List<DishVO>)valueOperations.get("user_category_" + dish.getCategoryId());
        if(dishVOS == null){
            List<Dish> dishList = dishMapper.list(dish.getCategoryId(),dish.getStatus());

            dishVOS = new ArrayList<>();//dishVOS若为null则初始化对象

            for (Dish d : dishList) {
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(d,dishVO);

                //根据菜品id查询对应的口味
                List<DishFlavor> flavors = dishFlavorMapper.deleteByFlavorId(d.getId());

                dishVO.setFlavors(flavors);
                dishVOS.add(dishVO);

            }
            valueOperations.set("user_category_" + dish.getCategoryId(),dishVOS);
        }

        return dishVOS;
    }
}
